import React, { useEffect, useRef, useState } from "react";

import {
  Button,
  DatePicker,
  Input,
  Layout,
  Pagination,
  Popconfirm,
  Select,
  Space,
  Tag,
  message,
  theme,
} from "antd";

import { DeleteOutlined } from "@ant-design/icons";

import {
  ModalForm,
  ProForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
} from "@ant-design/pro-components";
import Table, { ColumnsType } from "antd/es/table";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import dayjs from "dayjs";
import { useAppSelector } from "../../app/hooks";
import { RootState } from "../../app/store";
const { Content } = Layout;
const { RangePicker } = DatePicker;
export interface QueryCondition {
  username: string;
  role: string;
  phone: string;
  email: string;
  createBeginTime: number;
  createEndTime: number;
  updateBeginTime: number;
  updateEndTime: number;
}

// UserData
export interface UserDataType {
  id: string;
  username: string;
  password: string;
  email: string;
  phone: string;
  role: string;
  createtime: number;
  updatetime: number;
}

const App: React.FC = () => {
  interface RoleSelectOption {
    value: string;
    label: string;
  }
  /**
   *TODO:将这里的请求换成REDUX，这样就可以在一个页面请求到所有角色，并同时更改 >>>> 完成👌👌👌
   *
   */
  const roleList = useAppSelector((state: RootState) => state.role.roleMsg);

  function getRoleSelectOptions(): RoleSelectOption[] {
    const options: RoleSelectOption[] = [];
    roleList.map((role) => {
      const option: RoleSelectOption = {
        value: role.id,
        label: role.name,
      };
      options.push(option);
      return option;
    });
    return options;
  }

  // QueryFilter
  const [queryCondition, setQueryCondition] = useState<QueryCondition>({
    username: "",
    role: "",
    phone: "",
    email: "",
    createBeginTime: NaN,
    createEndTime: NaN,
    updateBeginTime: NaN,
    updateEndTime: NaN,
  } as QueryCondition);

  const handleSelectChange = (value: {
    value: string;
    label: React.ReactNode;
  }) => {
    setQueryCondition({ ...queryCondition, role: value.value });
  };

  function handleInputChange(e: any) {
    setQueryCondition({ ...queryCondition, username: e.target.value });
  }

  function handleCreateRangePickerChange(
    dates: any,
    dateString: [string, string]
  ) {
    setQueryCondition({
      ...queryCondition,
      createBeginTime: dates[0].valueOf(),
      createEndTime: dates[1].valueOf(),
    });
  }

  function handleUpdateRangePickerChange(
    dates: any,
    dateString: [string, string]
  ) {
    setQueryCondition({
      ...queryCondition,
      updateBeginTime: dates[0].valueOf(),
      updateEndTime: dates[1].valueOf(),
    });
  }

  const [KeyValue, setKey] = useState("0");

  function resetQuery() {
    setKey(new Date().getTime().toString());
    setQueryCondition({
      username: "",
      role: "",
      phone: "",
      email: "",
      createBeginTime: NaN,
      createEndTime: NaN,
      updateBeginTime: NaN,
      updateEndTime: NaN,
    });
    setIsQueryByCondition(false);
  }

  function query() {
    console.log("查询");
    setIsQueryByCondition(true);
    QueryByPage(1, pageSize);
  }

  // ModalForm
  const waitTime = (time: number = 10) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(true);
      }, time);
    });
  };

  async function UpdateOrAddUser(values: any) {
    await waitTime(1000);
    if (UserMorA === "add") {
      axios
        .post("/api/accounts", {
          username: values.username,
          role: values.role,
          password: values.password,
          email: values.email,
          phone: values.phone,
        })
        .then((response) => {
          if (response.status !== 200) {
            message.error("添加失败");
            return false;
          }
          QueryByPage(pageIndex, pageSize);
        });
      message.success("添加成功");
      setUserModalOpenState(false);
      return true;
    } else if (UserMorA === "update") {
      axios
        .put(`/api/accounts/${UserUpdateMsg.id}`, {
          username: values.username,
          role: values.role,
          password: values.password,
          email: values.email,
          phone: values.phone,
        })
        .then((response) => {
          if (response.status !== 200) {
            message.error("修改失败");
            return false;
          }
          QueryByPage(pageIndex, pageSize);
        });
      message.success("修改成功");
      setUserModalOpenState(false);
      return true;
    }
  }

  const [isUserModalOpen, setUserModalOpenState] = useState(false);
  const [UserMorA, setUserMorA] = useState("update");
  const [UserUpdateMsg, setUserUpdateMsg] = useState({} as UserDataType);
  const [selectedUser, setSelectedUser] = useState<string>("");
  const [isQueryByCondition, setIsQueryByCondition] = useState<boolean>(false);
  const restFormRef = useRef<ProFormInstance>();
  const ModalTitle = UserMorA === "update" ? "修改" : "添加";

  // 分页查询
  const columns: ColumnsType<UserDataType> = [
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
      render: (text, record) => (
        <a onClick={() => showUserUpdateMsg(record)}>{text}</a>
      ),
    },
    {
      title: "电话号码",
      dataIndex: "phone",
      key: "phone",
      render: (text, record) => <span> {text ? text : "\\"}</span>,
    },
    {
      title: "创建时间",
      dataIndex: "createtime",
      key: "createtime",
      render: (text, record) => (
        <>{dayjs(new Date(text)).format("YYYY年MM月DD日 HH:mm:ss")}</>
      ),
    },
    {
      title: "更新时间",
      dataIndex: "updatetime",
      key: "updatetime",
      render: (text, record) => (
        <>{dayjs(new Date(text)).format("YYYY年MM月DD日 HH:mm:ss")}</>
      ),
    },
    {
      title: "角色",
      key: "role",
      dataIndex: "role",
      render: (_, { role }) => (
        <>
          <Tag color={"blue"} key={role}>
            {roleOptions.map((item) => (item.value === role ? item.label : ""))}
          </Tag>
        </>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => OpenUpdateModal(record)}>编辑</a>
          <Popconfirm
            title={<DeleteOutlined />}
            description="你确定要删除这个成员吗?"
            onConfirm={() => confirm(record)}
            onCancel={cancel}
            okText="是"
            cancelText="否"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [data, setTableData] = useState([] as UserDataType[]);
  const [totalItems, setTotalItems] = useState(0);
  const navigate = useNavigate();

  // rowSelection object indicates the need for row selection
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: UserDataType[]) => {
      setSelectedUser(selectedRowKeys.toString());
    },
    getCheckboxProps: (record: UserDataType) => ({
      disabled: record.username === "Disabled User", // Column configuration not to be checked
      name: record.username,
    }),
  };

  function OpenUpdateModal(record: UserDataType) {
    setUserUpdateMsg(record);
    setUserModalOpenState(true);
    setUserMorA("update");
  }

  const confirm = (record: UserDataType) => {
    deleteUser(record);
  };

  const confirmDeleteUserByIds = () => {
    const idsArr = selectedUser.split(",")
    if(selectedUser.length>0){
      axios
      .delete("/api/accounts", {
        params: {
          ids: selectedUser,
        },
      })
      .then((response) => {
        if (response.status !== 200) {
          message.error("删除失败");
        } else {
          if(idsArr.length === data.length && pageIndex!==1 ){
            console.log("hahahh ");
            setPageIndex(pageIndex-1);
            QueryByPage(pageIndex-1, pageSize);
          }
          else{
            QueryByPage(pageIndex, pageSize)
          }
        }
      });
    }
    else{
      message.error("请至少选择一个成员")
    }

  };
  const cancel = (e: any) => {
    message.error("已取消");
  };

  function deleteUser(record: UserDataType) {
    axios.delete(`api/accounts/${record.id}`).then((response) => {
      if (response.status !== 200) {
        message.error("删除失败");
      } else {
        if (data.length === 1 && pageIndex !== 1) {
          QueryByPage(pageIndex - 1, pageSize);
        } else {
          QueryByPage(pageIndex, pageSize);
        }
      }
    });
  }

  function showUserUpdateMsg(record: UserDataType) {
    console.log("查看详情");
    navigate(`/userdetail?id=${record.id}`);
  }

  function OpenAddModal() {
    console.log("添加");
    setUserModalOpenState(true);
    setUserMorA("add");
    console.log("发送post请求");
  }

  const {
    token: { colorBgContainer },
  } = theme.useToken();

  function QueryByPage(page: number, pageSize: number) {
    setPageIndex(page);
    setPageSize(pageSize);
    if (isQueryByCondition) {
      let queryData: UserDataType[] = [];
      axios
        .get("/api/accounts", {
          params: {
            pageIndex: page - 1,
            pageSize: pageSize,
            username: queryCondition.username,
            email: queryCondition.email,
            phone: queryCondition.phone,
            role: queryCondition.role,
            createBeginTime: queryCondition.createBeginTime,
            createEndTime: queryCondition.createEndTime,
            updateBeginTime: queryCondition.updateBeginTime,
            updateEndTime: queryCondition.createEndTime,
          },
        })
        .then((response) => {
          setTotalItems(response.data.data.pageRow);
          queryData = response.data.data.result;
          setTableData(queryData);
        });
    } else {
      let initData: UserDataType[] = [];
      axios
        .get("/api/accounts", {
          params: {
            pageIndex: page - 1,
            pageSize: pageSize,
          },
        })
        .then((response) => {
          setTotalItems(response.data.data.pageRow);
          initData = response.data.data.result;
          setTableData(initData);
          setPageIndex(page);
          setPageSize(pageSize);
        });
    }
  }
  const roleOptions = getRoleSelectOptions();

  // Modal Form
  const phoneValidator = async (_: any, value: any) => {
    if (!value) {
      return Promise.resolve();
    }
    const phoneRegex = /^1[0-9]{10}$/;
    if (!phoneRegex.test(value)) {
      return Promise.reject("错误电话");
    }
    return Promise.resolve();
  };

  const emailValidator = async (_: any, value: any) => {
    const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
    if (!value) {
      return Promise.resolve();
    }
    if (!emailRegex.test(value)) {
      return Promise.reject("错误邮箱");
    }
    return Promise.resolve();
  };
  const validatePassword = async (_: any, value: any) => {
    if (!value) {
      return Promise.reject("请设置密码");
    }
    if (value.length < 6) {
      return Promise.reject("太短了");
    }
    return Promise.resolve();
  };

  const validateUsername = async (_: any, value: any) => {
    if (!value) {
      return Promise.reject("请设置用户名");
    }
    if (/\s/.test(value)) {
      return Promise.reject("名字不能含空格");
    }
    if (value.replace(/[^\x00-\xff]/g, "aa").length > 12) {
      return Promise.reject("名字太长了");
    }
    return Promise.resolve();
  };

  useEffect(() => {
    QueryByPage(1, 5);
  }, [isQueryByCondition]);

  return (
    <div>
      <div>
        <Space
          direction="horizontal"
          style={{ margin: "8px", paddingLeft: 24, paddingRight: 24 }}
        >
          <span>用户名:</span>
          <Input
            key={"input" + KeyValue}
            placeholder="用户名"
            onChange={handleInputChange}
          />
          <span>角色:</span>
          <Select
            key={"select" + KeyValue}
            labelInValue
            defaultValue={{
              label: "",
              value: "",
            }}
            style={{ width: 120 }}
            onChange={handleSelectChange}
            options={roleOptions}
          />
          <span>创建时间:</span>
          <RangePicker
            key={"createtime" + KeyValue}
            onChange={handleCreateRangePickerChange}
            allowClear={false}
            size="middle"
            style={{ width: "200px" }}
          />
          <span>更新时间:</span>
          <RangePicker
            key={"updatetime" + KeyValue}
            onChange={handleUpdateRangePickerChange}
            allowClear={false}
            style={{ width: "200px" }}
          />
          <Button type="primary" size="middle" onClick={query}>
            查询
          </Button>
          <Button size="middle" onClick={resetQuery}>
            重置
          </Button>
        </Space>
      </div>
      <Content
        style={{
          margin: "8px",
          padding: 24,
          minHeight: 280,
          background: colorBgContainer,
        }}
      >
        <div>
          <Space direction="horizontal">
            <Button type="primary" size="middle" onClick={OpenAddModal}>
              添加
            </Button>
            <Popconfirm
              title="Delete"
              description="你确定要删除这些成员?"
              onConfirm={confirmDeleteUserByIds}
              onCancel={cancel}
              okText="是"
              cancelText="否"
            >
              <Button danger type="primary" size="middle">
                删除
              </Button>
            </Popconfirm>
          </Space>
          <Table
            rowKey={(record) => {
              return record.id;
            }}
            rowSelection={{
              type: "checkbox",
              ...rowSelection,
            }}
            columns={columns}
            dataSource={data}
            sticky
            pagination={false}
            style={{ minWidth: "800px" }}
          />
        </div>
        <div>
          <ModalForm
            title={ModalTitle}
            open={isUserModalOpen}
            formRef={restFormRef}
            onFinish={UpdateOrAddUser}
            modalProps={{
              destroyOnClose: true,
              onCancel: () => console.log("run"),
            }}
            submitter={{
              searchConfig: {
                resetText: "重置",
              },
              resetButtonProps: {
                onClick: () => {
                  restFormRef.current?.resetFields();
                },
              },
            }}
            onOpenChange={setUserModalOpenState}
          >
            <ProForm.Group>
              <ProFormText
                width="md"
                name="username"
                label="用户名"
                tooltip="最长为 24 位"
                placeholder="请输入名称"
                initialValue={
                  UserMorA === "update" ? UserUpdateMsg.username : ""
                }
                rules={[
                  { required: true, validator: validateUsername },
                  { message: "请设置用户名" },
                ]}
              />
              <ProFormText.Password
                width="md"
                name="password"
                label="密码"
                placeholder="请输入密码"
                initialValue={
                  UserMorA === "update" ? UserUpdateMsg.password : ""
                }
                rules={[
                  { required: true, validator: validatePassword },
                  { message: "请设置密码" },
                ]}
              />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormText
                width="md"
                name="email"
                label="邮箱地址"
                placeholder="请输入邮箱地址"
                initialValue={UserMorA === "update" ? UserUpdateMsg.email : ""}
                rules={[
                  {
                    validator: emailValidator,
                  },
                ]}
              />
              <ProFormText
                width="md"
                name="phone"
                label="电话号码"
                placeholder="请输入电话号码"
                initialValue={UserMorA === "update" ? UserUpdateMsg.phone : ""}
                rules={[
                  {
                    validator: phoneValidator,
                  },
                ]}
              />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormSelect
                request={async () => roleOptions}
                width="xs"
                name="role"
                label="选择你的职位"
                initialValue={UserMorA === "update" ? UserUpdateMsg.role : ""}
                rules={[{ required: true }, { message: "请选择职位" }]}
              />
            </ProForm.Group>
          </ModalForm>
        </div>
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            margin: "16px 0",
            minWidth: "600px",
          }}
        >
          <Pagination
            total={totalItems}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `Total ${total} items`}
            onChange={QueryByPage}
            current={pageIndex}
            pageSize={pageSize}
            pageSizeOptions={[5, 10, 15, 20]}
          />
        </div>
      </Content>
    </div>
  );
};

export default App;
